import { Component, OnInit, Input, ElementRef, ViewChild, AfterViewInit, Output, EventEmitter } from '@angular/core';
import { PersonnelInfo, PersonnelService } from '../../services/personnel.service';
import { NgForm } from '@angular/forms';
import { markAllAsTouched, formGroupToFormData } from 'app/modules/base/helper';

@Component({
	selector: 'm-edit-card',
	templateUrl: './edit-card.component.html',
	styleUrls: ['./edit-card.component.scss'],
})
export class EditCardComponent implements OnInit {
	constructor(private personnelManager: PersonnelService) {}
	formData = this.personnelManager.formData;
	formGroup = this.personnelManager.formGroup;

	@Input() personnel: PersonnelInfo;
	@Output() cancel = new EventEmitter();
	@Output() saved = new EventEmitter();
	preview: string;

	ngOnInit() {
		this.formGroup.setValidators(null);
		['ldap_username', 'ldap_password', 'ldap_password_confirm'].forEach(name => this.formGroup.removeControl(name));

		this.formGroup.patchValue(this.personnel);
	}
	async submit() {
		markAllAsTouched(this.formGroup);
		if (this.formGroup.invalid) {
			return;
		}
		const data = formGroupToFormData(this.formGroup);
		await this.personnelManager.update(data);
		this.saved.emit();
	}
}
